/**
 * 右侧工具条js
 * */
define(function(require, exports, module) {
    var common = require("common");
    var template = require("template");

    /*-----------start 一些公共函数-------------------*/
    var $toolbar = $("#toolbar"),
        $toggle = $toolbar.find(".toggle"),
        $menu =$toolbar.find(".toolbar-menu"),
        $form =$toolbar.find("form.car_tb"),
        $close = $toolbar.find(".tb-close"),
        $tb = $toolbar.children(".toolbar-tb"),
        $checkAll = $toolbar.find(".c_all");


    //购物车对象
    var car = {
        getData: function () {
            common.ajaxHandle({
                url: '/member/order/getCart',
                isLoading: false,
                callback: function (item) {
                    var data = item.data,temp;
                    if(data.product.length>0) {
                        temp = template("carTemp",data);
                    }else {
                        temp = '<p class="tc" style="padding-top: 30px;">购物车空啦，快去购物吧～</p>'
                    }
                    $tb.addClass("loaded");
                    $tb.children(".tb-content").html(temp);
                    //全选
                    var $checkItem = $toolbar.find(".car_tb [type='checkbox']");
                    var $canCheck = $checkItem.not(":disabled");
                    common.checkBox($checkAll,$canCheck,$("#has_checkId"),function(){
                        $checkItem.each(function(i,e){
                            if($(e).is(":checked")) {
                                $(e).parents(".tr").find("input").not("[type='checkbox']").prop("disabled",false);
                            }else {
                                $(e).parents(".tr").find("input").not("[type='checkbox']").prop("disabled",true);
                            }
                        });
                        car.count_all();
                    });

                }
            })
        }, set_val : function($tr,num) {
            //设置相关值
            $tr.find(".num").val(num);
            var price = $tr.find(".price").html();
            var count = Number(price)*Number(num);
            $tr.find(".count").html(count.toFixed(2));
            this.count_all();
        },count_all : function() {
            //计算商品总量,与价格总量
            var all_count = 0;
            var all_num = 0 ;
            var $all_count = $(".all_count_t");
            var $all_num = $(".all_num_t");
            var $checked = $toolbar.find(".car_tb [type='checkbox']").filter(":checked");
            if($checked.length>0) {
                $checked.each(function () {
                    var count = $(this).parents(".tr").find(".count").html();
                    console.log(count);
                    var num = $(this).parents(".tr").find(".num").val();
                    all_count = all_count + Number(count);
                    all_num = all_num + Number(num);
                });
            }
            $all_count.html(all_count.toFixed(2));
            $all_num.html(all_num.toFixed(2));
        }
    };
    //数量计算框
    exports.numBox = function(){

        //加减操作
        $toolbar.on("click",".num_box .cut",function(){
            var tr = $(this).parents(".tr");
            var $num = tr.find(".num");
            var num = $num.val();
            if(num==1) return false;
            num--;
            var min = $num.data("min");
            if(num<min) {
                layer.alert("该商品的最小交易量为【"+min+"】吨");
                return false;
            }
            car.set_val(tr,num);
        });
        $toolbar.on("click",".num_box .add",function(){
            var tr = $(this).parents(".tr");
            var $num = tr.find(".num");
            var num = $num.val();
            num++;
            var max = $num.data("max");
            if(num>max) {
                layer.alert("该商品的库存仅为【"+max+"】吨");
                return false;
            }
            car.set_val(tr,num);
        });

        $toolbar.on("keyup",".num_box .num",function(){
            var tr = $(this).parents(".tr");
            var $num = tr.find(".num");
            var num = $num.val();
            var min = parseFloat($num.data("min"));
            var max = parseFloat($num.data("max"));

            //var num2 = clearNoNum($num);

            //var reg = /^[^1-9]|[^\d\.]+/g;
            var reg1 = /[^\d.]/g; //清除数字和“.” 以外的字符
            var reg2 = /(\.\d*)\./g; //清除两个以上的"."
            var reg3 = /^(\d+)\.(\d{0,3}).*$/; //清除三位以上的小数

            var num2 = num.replace(reg1,"").replace(reg2,"$1").replace(reg3,"$1.$2");
            if(num2==""){
                num2=min;
            }
            if(num2<min) {
                layer.alert("该商品的最小交易量为【"+min+"】吨");
                num2=min;
            }else if(num2>max) {
                layer.alert("该商品的库存仅为【"+max+"】吨");
                num2=max;
            }
            car.set_val(tr,num2);
        });

    };

    exports.init=function() {

        //初始化 数量操作框
        exports.numBox();
        //删除操作
        $toolbar.on("click",'[data-act="del"]',function(){
            var tr = $(this).parents(".tr");
            var id = $(this).data("id");
            layer.confirm("确定删除此商品吗？",{icon:3},function(layerIndex){
                var car_num = $(".carNum_id").html();
                if (car_num == "") {
                    car_num = 0;
                }
                common.ajaxHandle({
                    url: '/member/order/delCartProduct',
                    data:{id:id},
                    callback:function(){
                        car_num--;
                        $(".carNum_id").addClass("badge").html(car_num);
                        tr.find("[type='checkbox']").prop("checked",false);
                        tr.find("[type='checkbox']").trigger("change");
                        tr.remove();
                        layer.msg('删除成功');
                    }
                });
            });
        });
        /*购物车 提交订单*/
        $("#toolbar").on('click','[data-act="pay"]',function () {
            var size = $form.find("[type='checkbox']:checked").size();
            if(size<=0) {
                layer.alert("请选择至少一件商品！！");
                return false;
            }else {
                var attr=[],firstJson={},errorNum=0;
                var $checked = $form.find("[type='checkbox']:checked");
                var firstObj =  $checked.first();
                firstJson.delivery_way = firstObj.siblings("[name='delivery_way[]']").val();
                firstJson.repertory_id = firstObj.siblings("[name='repertory_id[]']").val();

                $checked.each(function(i,e){
                    var $this = $(this);
                    var json = {};
                    json.delivery_way = $this.siblings("[name='delivery_way[]']").val();
                    json.repertory_id = $this.siblings("[name='repertory_id[]']").val();

                    if(firstJson.delivery_way!=json.delivery_way) {
                        common.error("所选产品不是同一种交收方式,不允许提交订单");
                        errorNum++;
                        return false;
                    }else if(firstJson.repertory_id!=json.repertory_id) {
                        common.error("所选产品不在同一个交收仓,不允许提交订单");
                        errorNum++;
                        return false;
                    }
                });
                if(errorNum===0) {
                    $form.submit();
                }
            }
        });

        /*=======================购物车悬浮栏事件=================*/
        $toggle.on("click", function () {
            var $this = $(this);
            var active = $this.hasClass("active");
            var scroll_bh = $(".tb-bottom").height() + 100;
            //最大高度
            var scroll_h = $(window).height() - scroll_bh + "px";
            //当前显示列数
            var con_li_h = $(".tb-content").children().length;
            //如果没有，那么购物车隐藏
            if (active) {
                $toolbar.animate({right: "-280px"}, 500);
                $tb.removeClass("loaded");
                $toolbar.find(".tb_m_off").addClass("none");
            }
            //如果有，那么购物车展出
            else {
                car.getData();
                $toolbar.animate({right: "0"}, 400);
                $(".tb-content").css({'height': scroll_h});
                $toolbar.find(".tb_m_off").removeClass("none");

                /*购物车显示列数*/
                /* if (con_li_h > 4) {
                 $(".tb-content").css({'overflow-y': 'visible'});
                 }
                 else {
                 $(".tb-content").css({'overflow-y': 'hidden'});
                 }*/
            }
            $toggle.toggleClass("active");
        });

        //失去焦点隐藏
        /*  $(document).on('click',function(e){
         //(e.target) ? e.target.id : e.srcElement.id;id);

         //$toggle.trigger("click");
         });*/
        /**
         * 工具条返回顶部
         */
        $toolbar.on("click", ".top", function () {
            $("html,body").animate({scrollTop: 0});
        });
        /*=======================end购物车悬浮栏事件=================*/
    }

});